package com.jiliason.testTools;

import com.google.common.collect.Lists;

import com.jiliason.testTools.entity.TestDataPojo;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Component
public class ModuleTestDataLoad implements TestDataLoader {

    @Resource
    private ResourceLoader resourceLoader;

    @Override
    public <T> List<TestDataPojo> loadTestData(T t) throws Exception {
        if (t instanceof String) {
            return getTestData((String) t);
        }
        return Lists.newArrayList();
    }

    @Override
    public List<TestDataPojo> loadTestData() {
        return Lists.newArrayList();
    }

    public List<TestDataPojo> getTestData(String testResources) throws IOException {
        org.springframework.core.io.Resource resource = this.resourceLoader.getResource(resourceLoader.CLASSPATH_URL_PREFIX + testResources);
        Path path = resource.getFile().toPath();
        if (Files.isRegularFile(path)) return Collections.unmodifiableList(InitTestData.getTestDataByPath(path));
        PathMatchingResourcePatternResolver s = new PathMatchingResourcePatternResolver();
        List<org.springframework.core.io.Resource> l = Arrays.stream(s.getResources(ResourceUtils.CLASSPATH_URL_PREFIX + testResources + "/**/*"))
                .filter(org.springframework.core.io.Resource::isFile)
                .filter(r -> Objects.requireNonNull(r.getFilename()).endsWith(".txt"))
                .toList();

        List<TestDataPojo> res = Lists.newArrayList();

        for (org.springframework.core.io.Resource r : l) {
            List<TestDataPojo> temp = InitTestData.getTestDataByPath(r.getFile().toPath());
            res.addAll(temp);
        }
        return Collections.unmodifiableList(res);
    }
}
